package com.xiaotao.util;

import com.xiaotao.entity.TeamPost;
import com.xiaotao.entity.UserPreference;
import com.xiaotao.mapper.TeamPostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class RecommendUtil {

    @Autowired
    private TeamPostMapper teamPostMapper;

    /**
     * 为指定用户获取推荐帖子
     */
    public List<TeamPost> getRecommendedPosts(Integer userId) {
        List<TeamPost> allPosts = teamPostMapper.selectAllActivePosts();

        if (allPosts.isEmpty()) {
            return new ArrayList<>();
        }

        // 如果没有用户ID，返回热门帖子
        if (userId == null) {
            return getHotPosts(allPosts);
        }

        // 计算每个帖子的推荐分数
        Map<TeamPost, Integer> postScores = new HashMap<>();
        for (TeamPost post : allPosts) {
            int score = calculatePostScore(post, userId);
            postScores.put(post, score);
        }

        // 按推荐分数排序返回前20个
        return postScores.entrySet().stream()
                .sorted((a, b) -> b.getValue() - a.getValue())
                .limit(20)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

    /**
     * 计算所有帖子的推荐分数（用于定时任务）
     */
    public void calculateAllRecommendScores() {
        List<TeamPost> allPosts = teamPostMapper.selectAllActivePosts();

        for (TeamPost post : allPosts) {
            // 基于热度计算基础分数
            int score = calculateHotScore(post);
            post.setRecommendScore(score);
            teamPostMapper.updateRecommendScore(post);
        }
    }

    /**
     * 计算帖子热度分数
     */
    private int calculateHotScore(TeamPost post) {
        int baseScore = 0;

        // 点赞数权重（每个点赞10分）
        baseScore += post.getLikeCount() * 10;

        // 浏览量权重（每次浏览1分）
        baseScore += post.getViewCount() * 1;

        // 申请数权重（每个申请5分）
        baseScore += post.getApplyCount() * 5;

        // 时效性：新帖子加分
        long hoursSinceCreation = ChronoUnit.HOURS.between(
                post.getCreateTime(), LocalDateTime.now());

        if (hoursSinceCreation < 24) {
            baseScore += 50; // 24小时内发布的帖子
        } else if (hoursSinceCreation < 168) {
            baseScore += 20; // 一周内发布的帖子
        }

        return Math.max(0, baseScore);
    }

    /**
     * 计算单个帖子的综合推荐分数
     */
    private int calculatePostScore(TeamPost post, Integer userId) {
        int score = calculateHotScore(post);

        // 1. 分类匹配（权重：30%）
        double categoryMatchScore = calculateCategoryMatchScore(post, userId);
        score += (int)(categoryMatchScore * 30);

        // 2. 标签匹配（权重：25%）
        double tagMatchScore = calculateTagMatchScore(post, userId);
        score += (int)(tagMatchScore * 25);

        // 3. 地理位置匹配（权重：20%）
        double locationMatchScore = calculateLocationMatchScore(post, userId);
        score += (int)(locationMatchScore * 20);

        // 4. 时间匹配（权重：15%）
        double timeMatchScore = calculateTimeMatchScore(post);
        score += (int)(timeMatchScore * 15);

        // 5. 用户行为修正（基于历史行为）
        double behaviorScore = calculateBehaviorScore(post, userId);
        score += (int)(behaviorScore * 10);

        return Math.max(0, score);
    }

    /**
     * 分类匹配分数
     */
    private double calculateCategoryMatchScore(TeamPost post, Integer userId) {
        // 简化实现：如果用户之前点赞过同分类帖子，给高分
        List<TeamPost> userLikedPosts = teamPostMapper.selectUserLikedPosts(userId);
        long sameCategoryCount = userLikedPosts.stream()
                .filter(p -> p.getCategory().equals(post.getCategory()))
                .count();

        if (sameCategoryCount > 0) {
            return 0.8;
        }
        return 0.3;
    }

    /**
     * 标签匹配分数
     */
    private double calculateTagMatchScore(TeamPost post, Integer userId) {
        List<TeamPost> userLikedPosts = teamPostMapper.selectUserLikedPosts(userId);
        List<String> postTags = post.getTagsAsList();

        if (postTags.isEmpty()) {
            return 0.3;
        }

        // 计算用户历史喜欢的标签
        Set<String> userPreferredTags = userLikedPosts.stream()
                .flatMap(p -> p.getTagsAsList().stream())
                .collect(Collectors.toSet());

        long matchedTags = postTags.stream()
                .filter(userPreferredTags::contains)
                .count();

        if (matchedTags > 0) {
            return 0.3 + (matchedTags * 0.2); // 每个匹配标签加0.2分
        }

        return 0.3;
    }

    /**
     * 地理位置匹配分数
     */
    private double calculateLocationMatchScore(TeamPost post, Integer userId) {
        // 简化实现：给固定分数，实际应该基于用户位置
        return 0.5;
    }

    /**
     * 时间匹配分数
     */
    private double calculateTimeMatchScore(TeamPost post) {
        LocalDateTime now = LocalDateTime.now();

        // 活动即将开始（未来24小时内）给高分
        if (post.getStartTime() != null) {
            long hoursToStart = ChronoUnit.HOURS.between(now, post.getStartTime());
            if (hoursToStart >= 0 && hoursToStart <= 24) {
                return 0.9;
            } else if (hoursToStart > 24 && hoursToStart <= 168) {
                return 0.7; // 一周内的活动
            }
        }

        return 0.5;
    }

    /**
     * 用户行为修正分数
     */
    private double calculateBehaviorScore(TeamPost post, Integer userId) {
        // 检查用户是否已经申请过或点赞过
        boolean hasLiked = teamPostMapper.checkUserLikePost(userId, post.getId()) > 0;
        if (hasLiked) {
            return 0.8;
        }
        return 0.5;
    }

    /**
     * 获取热门帖子
     */
    private List<TeamPost> getHotPosts(List<TeamPost> posts) {
        return posts.stream()
                .sorted((a, b) -> {
                    int scoreA = a.getLikeCount() * 10 + a.getViewCount() + a.getApplyCount() * 5;
                    int scoreB = b.getLikeCount() * 10 + b.getViewCount() + b.getApplyCount() * 5;
                    return scoreB - scoreA;
                })
                .limit(20)
                .collect(Collectors.toList());
    }
}